package com.jlkf.service.impl.website;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jlkf.common.ExportExcel;
import com.jlkf.dao.CityRecordMapper;
import com.jlkf.dao.DriverTurnoverMapper;
import com.jlkf.dao.OrderChargeDetailMapper;
import com.jlkf.dao.OrderItemsMapper;
import com.jlkf.dao.StarRemarkMapper;
import com.jlkf.dao.UserCouponMapper;
import com.jlkf.dao.UserMapper;
import com.jlkf.dao.UserMessageFormworkMapper;
import com.jlkf.dao.UserMessageMapper;
import com.jlkf.pojo.CityRecord;
import com.jlkf.pojo.DriverTurnover;
import com.jlkf.pojo.OrderChargeDetail;
import com.jlkf.pojo.OrderItems;
import com.jlkf.pojo.StarRemark;
import com.jlkf.pojo.User;
import com.jlkf.pojo.UserCoupon;
import com.jlkf.pojo.UserMessage;
import com.jlkf.pojo.UserMessageFormwork;
import com.jlkf.service.WebsiteOrderItemsService;
import com.jlkf.service.util.DateUtil;
import com.jlkf.service.util.RegexUtil;
import com.jlkf.service.util.SendmailUtil;
import com.jlkf.service.util.StringTools;
import com.jlkf.view.ExportOrderView;
import com.platform.server.response.response.pojo.ReturnData;
import com.platform.server.util.RandomUtil;
@Service
public class WebsiteOrderItemsServiceImpl implements WebsiteOrderItemsService{

	@Autowired
	private OrderItemsMapper orderItemsMapper;
	@Autowired
	private StarRemarkMapper starRemarkMapper;
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private UserMessageFormworkMapper userMessageFormworkMapper;
	@Autowired
	private UserCouponMapper userCouponMapper;
	@Autowired
	private OrderChargeDetailMapper orderChargeDetailMapper;
	@Autowired
	private CityRecordMapper cityRecordMapper; 
	@Autowired
    private DriverTurnoverMapper driverTurnoverMapper;
	@Autowired
	private UserMessageMapper userMessageMapper;
	//乘客的订单列表
		@Override
		public Object getPassengerOrderList(Integer pageNo, Integer pageSize, String orderNo, String startTime,
				String endTime,Long uId) {
			Map<String,Object> map = new HashMap<>();
			if(RegexUtil.isNull(pageNo)){
				pageNo=1;
			}
			if(RegexUtil.isNull(pageSize)){
				pageSize=15;
			}
			if(!StringTools.isEmpty(orderNo)){
				map.put("orderNo", orderNo);
			}
			if(!StringTools.isEmpty(startTime)&&!StringTools.isEmpty(endTime)){
				map.put("startTime", startTime);map.put("endTime", endTime);
			}
			if(!RegexUtil.isNull(uId)){
				map.put("uId", uId);
			}
			Map<String,Object> map1 = null;
//			map.put("status", 8);
			 List<OrderItems> resultlist =new ArrayList<>();
			try {
//				map.put("starRemarkType", 2);//类别 1司机评价 2app用户评价
				 PageHelper.startPage(pageNo, pageSize);
				 List<OrderItems> list = orderItemsMapper.websiteOrderDetails(map);
				 for(OrderItems oi:list){
					  map1 = new HashMap<>();
					  map1.put("orderId", oi.getId());
					  map1.put("type", 2);
					  map1.put("uId", uId);
					  List<StarRemark> li= starRemarkMapper.getStarRemarkList1(map1);
					  if(li.size()>0){
						  oi.setStar(li.get(0).getStar()+"");
						  oi.setContent(li.get(0).getContent());
					  }
				 }
				 PageInfo<OrderItems> info = new PageInfo(list);
				 Integer pages=info.getPages();
				 Integer totalRecord = (int) info.getTotal();
				 return new ReturnData(list,pages,totalRecord,200,"order_list");
			} catch (Exception e) {
				e.printStackTrace();
				return new ReturnData(500, "Wow, that's wrong ");
			}
		}
		//订单详情
		@Override
		public Object getOrderItemsDetails(Long orderId) {
			if(RegexUtil.isNull(orderId)){
				return new ReturnData(201,"The order id cannot be empty.");
			}
			Map<String,Object> map1 = new HashMap<>();
			map1.put("orderId", orderId);
			try {
				List<OrderItems> oi=orderItemsMapper.websiteOrderDetails(map1);//订单
				return new ReturnData(oi.get(0),200,"order_detail");
			} catch (Exception e) {
				e.printStackTrace();
				return new ReturnData(500, "Wow, that's wrong ");
			}
		}
		@Override
		public Object getOrderItemsDriverList(Integer pageNo, Integer pageSize, String orderNo, String startTime,
				String endTime, Long driverId) {
			Map<String,Object> map = new HashMap<>();
			if(RegexUtil.isNull(pageNo)){
				pageNo=0;
			}
			if(RegexUtil.isNull(pageSize)){
				pageSize=15;
			}
			if(!StringTools.isEmpty(orderNo)){
				map.put("orderNo", orderNo);
			}
			if(!StringTools.isEmpty(startTime)&&!StringTools.isEmpty(endTime)){
				map.put("startTime", startTime);map.put("endTime", endTime);
			}
			if(!RegexUtil.isNull(driverId)){
				map.put("driverId", driverId);
			}
			Map<String,Object> map1 = null;
			try {
				//map.put("starRemarkType", 1);//类别 1司机评价 2app用户评价
				 PageHelper.startPage(pageNo, pageSize);
				 List<OrderItems> list = orderItemsMapper.websiteOrderDetails(map);
				 for(OrderItems oi:list){
					  map1 = new HashMap<>();
					  map1.put("orderId", oi.getId());
					  map1.put("type", 2);
					  map1.put("byEvaluation", driverId);
					  List<StarRemark> li= starRemarkMapper.getStarRemarkList1(map1);
					  if(li.size()>0){
						  oi.setStar(li.get(0).getStar()+"");
						  oi.setContent(li.get(0).getContent());
					  }
				 }
				 PageInfo<OrderItems> info = new PageInfo(list);
				 Integer pages=info.getPages();
				 Integer totalRecord = (int) info.getTotal();
				 return new ReturnData(list,pages,totalRecord,200,"order_list");
			} catch (Exception e) {
				e.printStackTrace();
				return new ReturnData(500, "Wow, that's wrong ");
			}
		}
		@Override
		public void downloadOrder(HttpServletResponse response, HttpServletRequest request, String userOrderNo,
				String orderNo, String startTime, String endTime, Long uId,Long driverId) {
			Map<String,Object> map = new HashMap<>();
			if(!StringTools.isEmpty(orderNo)){
				map.put("orderNo", orderNo);
			}
			if(!StringTools.isEmpty(startTime)&&!StringTools.isEmpty(endTime)){
				map.put("startTime", startTime);map.put("endTime", endTime);
			}
			if(!RegexUtil.isNull(uId)){
				map.put("uId", uId);
			}
			if(!RegexUtil.isNull(driverId)){
				map.put("dirberId", driverId);
			}
			try {
				map.put("starRemarkType", 2);//类别 1司机评价 2app用户评价
				List<OrderItems> list = orderItemsMapper.websiteOrderDetails(map);
				List<Object> list1 = new ArrayList<>();
				 for(OrderItems oi:list){
					 ExportOrderView eov = new ExportOrderView();
					 eov.setArrivedLocation(oi.getArrivedLocation());
					 eov.setCarType(getCarType(oi.getCarType()));
					 eov.setCreateTime(DateUtil.format(oi.getCreateTime(), "yyyy-MM-dd hh:mm"));
					 eov.setDepartureLocation(oi.getDepartureLocation());
					 eov.setOrderStatus(getOrderStatus(oi.getStatus()));
					 eov.setDriverName(oi.getDriverName());
					 Double to=oi.getMileage()/1000;
					 eov.setMileage(to);
					 eov.setOrderNo(oi.getOrderNo());
					 eov.setRefundsPrice(oi.getRefundsPrice());//退款金额
					 eov.setStarRating(oi.getStar()+"");
					 eov.setTotalPrice(oi.getTotalPrice());
					 eov.setWayToPlace(oi.getWayToPlace());
					 list1.add(eov);
				 }
				 String[] Title = {"Order number","Created at", "Order status", "Pick up address", "Extra stop", "Destination address", "Distance (KM)", "Service category","Drivers name","Total paid","Refund","Reviews","Tips"};
			    ExportExcel.exportExcel("Rider’s information.xls", Title, list1, response);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		//订单状态
		private String getOrderStatus(Integer status){
			String result="";
			switch (status) {
			case 1:
				result="Waiting for order";
				break;
			case 2:
				result="Order confirmed ( Driver Confirmed)";
				break;
			case 3:
				result="On Route to pick up point";
				break;
			case 4:
				result="Arrived at pick up point";
				break;
			case 5:
				result="Rider on board";
				break;
			case 7:
				result="Order completed, waiting for payment";
				break;
			case 8:
				result="Completed (waiting for review)";
				break;
			case 9:
				result="Completed (reviewed)";
				break;
			case 10:
				result="Canceled (Free of charge)";
				break;
			case 11:
				result="Canceled (waiting for payment)";
				break;
			case 12:
				result="Canceled (paid)";
				break;
			case 13:
				result="Paid";
				break;
			case 14:
				result="Order completed, outstanding payment. Insufficient fund.";
				break;
			case 15:
				result="The driver ended the service, did not confirm the cost";
				break;
			}
			return result;
		}
		private String getCarType(Integer carType){
			String str="";
			switch (carType) {
			case 1:
				str="fab ONE";
				break;
			case 2:
				str="fab";
				break;
			case 3:
				str="fab PRO";
				break;
			}
			return str;
		}
		
		//乘客推送邮件
		@Override
		public Object pushEmail(Long orderId,Integer type) {
			Map<String,Object> mm = new HashMap<>();
			try {
				OrderItems oi=orderItemsMapper.selectByPrimaryKey(orderId);
				Long uId =null;
				if(type==1){
					uId = oi.getuId();
				}else{
					uId = oi.getDirberId();
				}
				User u = userMapper.selectByPrimaryKey(uId);
				mm.put("orderId", orderId);
				List<OrderChargeDetail> ocdl=orderChargeDetailMapper.getOrderChargeDetail(mm);
				String str="";
				if(ocdl.size()>0){
					str+="<p style='    padding: 10px;  margin-left: 37px;  font-size: x-large;'> Your Fare</p><ul style='list-style-type: none;  margin-left: 40px;'>";
					if(ocdl.get(0).getMileage()!=0){
						str+="<li style='padding: 10px;'>ileage fee:"+ocdl.get(0).getMileage()+"</li>";
					}
					if(ocdl.get(0).getTimeFee()!=0){
						str+= "<li style='padding: 10px;'>time fee:"+ocdl.get(0).getTimeFee()+"</li>";
					}
					if(ocdl.get(0).getStartFee()!=0){
						str+= "<li style='padding: 10px;'>Base Fare:"+ocdl.get(0).getStartFee()+"</li>";
					}
					if(ocdl.get(0).getCleanness()!=0){
						str+= "<li style='padding: 10px;'>cleanness :"+ocdl.get(0).getCleanness()+"</li>";
					}	
					if(ocdl.get(0).getTip()!=0){
						str+= "<li style='padding: 10px;'>tip :"+ocdl.get(0).getTip()+"</li>";
					}	
					if(ocdl.get(0).getMinimumFare()!=0){
						str+="<li style='padding: 10px;'>Minimum Fare:"+ocdl.get(0).getMinimumFare()+"</li>";
					}
					str+="<li style='padding: 10px;'>Subtotal:"+ocdl.get(0).getTotalMoney()+"</li></ul>";
				}
				System.out.println(oi.getCreateTime());
				int m=DateUtil.getTimeByCalendar(2,oi.getCreateTime());
				int d=DateUtil.getTimeByCalendar(3,oi.getCreateTime());
				String content="<p> </p>"
						+ "<div style='    width: 500px;  height: 300px; margin-left: 40px; background-color: #f3eded;'><p>$"+oi.getTotalPrice()+"</p>"
						+ "<p>Thanks for choosing FAB, "+oi.getName()+"</p>"
						+ "<p style='margin-left: 40px;'>"+(m+1)+" "+d+", 2017 | FAB</p>"
						+ "<p style='margin-left: 40px;'>Starting point:"+oi.getArrivedLocation()+"</p>"
						+ "<p style='margin-left: 40px;'>terminus:"+oi.getDepartureLocation()+"</p>"
						+"</div><div style='    width: 500px;  height: 300px; margin-left: 40px; background-color: #f3eded;'>"+str+"</div>";
				SendmailUtil.sendEmail("Trip "+DateUtil.format(oi.getCreateTime(), "dd/MM/yyyy")+" details", content, "miqin_1993@163.com");
				return new ReturnData(200,"success");
			} catch (Exception e) {
				e.printStackTrace();
				return new ReturnData(500,"Wow, that's wrong");
			}
		}
		//网站的消息模板
		@Override
		public Object getWebsiteFormworkList(Integer pageNo, Integer pageSize, String formworkName) {
			Map<String,Object> map = new HashMap<>();
			if(!StringTools.isEmpty(formworkName)){
				map.put("formworkName", formworkName);
			}
			if(RegexUtil.isNull(pageSize)){
				pageSize=10;
			}
			if(RegexUtil.isNull(pageNo)){
				pageNo=1;
			}
			try {
				PageHelper.startPage(pageNo, pageSize);
				List<UserMessageFormwork> list = userMessageFormworkMapper.getList(map);
				PageInfo<UserMessageFormwork> info = new PageInfo<>(list);
			int	pages=info.getPages();
			int totalRecord = (int) info.getTotal();
			return new ReturnData(list,pages,totalRecord,200,"userMessageFormwork_list");
			} catch (Exception e) {
				e.printStackTrace();
				return new ReturnData(500,"Wow, that's wrong");
			}
		}
		
		@Override
		public Object websiteFormworkAdd(String json) {
			UserMessageFormwork umf = StringTools.json2Obj(json, UserMessageFormwork.class);
			if(umf==null){
				return new ReturnData(201,"List must be filled");
			}
			try {
				umf.setCreateTime(new Date());
				int num=userMessageFormworkMapper.insertSelective(umf);
				if(num==0){
					return new ReturnData(202,"Failed to add");
				}
				return new ReturnData(200,"Added");
			} catch (Exception e) {
				e.printStackTrace();
				return new ReturnData(500,"Wow, that's wrong");
			}
		}
		
		//网站送优惠劵添加
		@Override
		public Object websiteCorporateCouponsAdd(String json) {
			UserCoupon uc= StringTools.json2Obj(json, UserCoupon.class);
			if(uc==null){
				return new ReturnData(201,"List must be filled");
			}
			Map<String,Object> map = new HashMap<>();
			String telephone=uc.getTelephone();
			map.put("telephone", telephone);
			map.put("identity", 1); int code=200;String msg="Gift sent";
			try {
				User qy = userMapper.selectByPrimaryKey(uc.getEnterpriseId());
				if(qy==null){
				return new ReturnData(300,"Business ID error, ID not exist");
				}
				Integer availableMoney=	qy.getAvailableMoney();//企业的可用金额
				BigDecimal couponOffsetMoney =uc.getCouponOffsetMoney();
				Integer amount_given=(int) (couponOffsetMoney.doubleValue()*Integer.parseInt(uc.getGenerationNum()));//本次需要赠送的金额
				 if(amount_given>availableMoney){
					 return new ReturnData(206,"Insufficient Gift Balance, The current available balance is $"+availableMoney);
				 }
				List<User> u = userMapper.getLogin(map);
				if(u.size()==0){
					return new ReturnData(203,"Rider account does not exist");
				}
				int n=Integer.parseInt(uc.getGenerationNum());
				uc.setuId(u.get(0).getId().toString());
				uc.setCreateTime(new Date());
				uc.setCouponMoney(uc.getCouponOffsetMoney());
				uc.setType(3);
				for(int i=0;i<n;i++){
					uc.setGenerationNum(1+"");
					uc.setCouponName("Business Gift coupons");
					String no=userCouponMapper.getMaxNo();
					if(StringTools.isEmpty(no)){
						no="YOU00001";
					}else{
						Integer no1 =Integer.parseInt(no)+1;
						if(no1<10){
							no = "YOU0000"+no1;
						}else if(no1>=10&no1<100){
							no = "YOU000"+no1;
						}else if(no1>=100&no1<1000){
							no = "YOU00"+no1;
						}else if(no1>=1000&no1<10000){
							no = "YOU0"+no1;
						}else{
							no = "YOU"+no1;
						}
					}
					uc.setCouponNo(no);
					uc.setCouponCode(RandomUtil.getRandomNumberNozeroStart(11));
					int num = userCouponMapper.insertSelective(uc);
					if(num==0){
						  code=282;msg="failed to send Gift";
					  }else{
						  Integer ye=availableMoney-amount_given;
							qy.setAvailableMoney(ye);
							int nu=userMapper.updateByPrimaryKeySelective(qy);//更新企业的可用余额
						  if(nu==0){
							  code=280;msg="failed to send Gift";
						  }
					  }
					if(code!=200){
						  TransactionAspectSupport.currentTransactionStatus().isRollbackOnly();
					  }
				}
				UserMessage um = new UserMessage();
				um.setCreateTime(new Date());
				um.setmContext(uc.getRemark());
				um.setmSummary("Companies give coupons.");
				um.setName(uc.getTelephone());
				um.setReleaseName(uc.getEnterpriseNo());
				um.setType(1);
				um.setuId(u.get(0).getId());
				um.setmName("Companies give coupons.");
				userMessageMapper.insertSelective(um);
				return new ReturnData(code,msg);
			} catch (Exception e) {
				e.printStackTrace();
				return new ReturnData(500,"Wow, that's wrong");
			}
		}
		@Override
		public Object getWebsiteCorporateCouponsList(Integer pageNo, Integer pageSize, String telephone,
				String startTime, String endTime, Integer isUse,Long enterpriseId) {
			Map<String,Object> map = new HashMap<>();
			if(RegexUtil.isNull(pageNo)){
				pageNo=1;
			}
			if(RegexUtil.isNull(pageSize)){
				pageSize=15;
			}
			if(!StringTools.isEmpty(telephone)){
				map.put("telephone", telephone);
			}
			if(!StringTools.isEmpty(startTime)&&!StringTools.isEmpty(endTime)){
				map.put("startTime", startTime);map.put("endTime", endTime);
			}
			if(!RegexUtil.isNull(enterpriseId)){
				map.put("enterpriseId", enterpriseId);
			}
			if(!RegexUtil.isNull(isUse)){
				map.put("isUse", isUse);
			}
			try {
				 map.put("type", 3);
				 PageHelper.startPage(pageNo, pageSize);
				 List<UserCoupon> list=userCouponMapper.getWebsiteCorporateCouponsList(map);
				 PageInfo<UserCoupon> info = new PageInfo<>(list);
				 int pages=info.getPages();
				 int totalRecord = (int) info.getTotal();
				 return new ReturnData(list,pages,totalRecord,200,"userCoupon_list");
			} catch (Exception e) {
				e.printStackTrace();
				return new ReturnData(500,"Wow, that's wrong");
			}
		}
		
		@Override
		public Object getCity() {
			Map<String,Object> map = new HashMap<>();
			try {
				List<CityRecord> list=cityRecordMapper.getList(map);
				return new ReturnData(list,200,"city_list");
			} catch (Exception e) {
				e.printStackTrace();
				return new ReturnData(500,"Wow, that's wrong");
			}
		}
		@Override
		public Object getWebsiteCorporateCouponsCount(Long enterpriseId) {
			try {
				String count=userCouponMapper.getWebsiteCorporateCouponsCount(enterpriseId);
				return new  ReturnData(count,200,"success");
			} catch (Exception e) {
				e.printStackTrace();
				return new ReturnData(500,"Wow, that's wrong");
			}
		}
		@Override
		public Object websiteDriverStatements(Long driverId) {
			Map<String,Object> map = new HashMap<>();
			DriverTurnover params = new DriverTurnover();
			params.setDriverId(driverId);
			 try {
				 List<Map> list= driverTurnoverMapper.websiteStatements(params);
				 return new ReturnData(list,200,"success");
			} catch (Exception e) {
				e.printStackTrace();
				return new ReturnData(500,"Wow, that's wrong");
			}
			 
		}
		
	
}
